<template>
	<uv-upload :fileList="data.fileList1" :accept="jType" name="1" multiple :maxCount="jNum" :previewFullImage="true"
		@afterRead="afterRead" @delete="deletePic"></uv-upload>
</template>
<script setup>
	import {
		reactive
	} from 'vue';
	import {
		showToast
	} from '@/utils/tools.js';
	import {
		imgUrl,
		getToken
	} from '@/util/request/url.js'
	const props = defineProps({
		jType: {
			type: String,
		},
		jImgs: {
			type: Array,
			default: []
		},
		jNum: {
			type: Number,
			default: 1
		}
	});


	const emits = defineEmits(['addFiles', 'deleteFiles'])


	const data = reactive({
		fileList1: props.jImgs,
		csToken: uni.getStorageSync('csToken'),
		entToken: uni.getStorageSync('entToken'),
	})

	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: imgUrl(), //
				filePath: url,
				name: 'file',
				header: {
					Authorization: getToken()
				},
				success: (res) => {
					let b = null

					b = JSON.parse(res.data)
					console.log(b, '上传');
					if (res.statusCode == 200) {

						resolve(b.data)
					}
					if (res.statusCode == 401) {
						showToast('登录已过期')
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}
					if (res.statusCode == 500) {
						showToast('服务器繁忙')
						resolve(null)
					}
				},
				fail(error) {
					console.log(error);
				}
			});
		})
	}

	// 删除图片
	const deletePic = (event) => {
		data[`fileList${event.name}`].splice(event.index, 1)

		emits('deleteFiles', event.index)

	};
	// 新增图片
	const afterRead = async (event) => {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		console.log(event);
		let lists = [].concat(event.file)
		let fileListLen = data[`fileList${event.name}`].length
		lists.map((item) => {
			data[`fileList${event.name}`].push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url)
			let item = data[`fileList${event.name}`][fileListLen]
			data[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: result ? result.url : '',
				eid: result ? result.eid : ''
			}))
			fileListLen++
		}


		data.fileList1 = data.fileList1.filter((item, index) => {
			return item.url
		})

		// console.log('上传成功', data.fileList1);

		emits('addFiles', data.fileList1)
	};
</script>
<style lang="scss" scoped>

</style>